<?php
namespace app\index\service;
use think\Session;
use app\model\GoodsCate;
use app\model\Goods;
use app\model\Collect;
use app\model\User;
use app\model\Order;
use think\Paginator;
// use think\Cache;
// use think\Log;

class IndexService{
    public function getParam($param)
    {
        // dump($param);die;
        $data = [];
        if(array_key_exists('keywords',$param) && $param['keywords'] != ''){
            $data['keywords'] = $param['keywords'];
        }else{
            $data['keywords'] = 0;
        }
        if(array_key_exists('sale_type',$param) && $param['sale_type'] != 'undefined'){
            $data['sale_type'] = $param['sale_type'];
        }else{
            $data['sale_type'] = 1;
        }
        if(array_key_exists('cate_id',$param) && $param['cate_id'] != 'undefined'){
            $data['cate_id'] = $param['cate_id'];
        }else{
            $data['cate_id'] = 0;
        }
        if(array_key_exists('price1',$param) && $param['price1'] != 'undefined'){
            $data['price1'] = $param['price1'];
        }else{
            $data['price1'] = 0;
        }
        if(array_key_exists('price2',$param) && $param['price2'] != 'undefined'){
            $data['price2'] = $param['price2'];
        }else{
            $data['price2'] = 0;
        }
        if(array_key_exists('coupon_price',$param) && $param['coupon_price'] != 'undefined'){
            $data['coupon_price'] = $param['coupon_price'];
        }else{
            $data['coupon_price'] = 0;
        }
        if(array_key_exists('commision',$param) && $param['commision'] != 'undefined'){
            $data['commision'] = $param['commision'];
        }else{
            $data['commision'] = 0;
        }
        if(array_key_exists('sale_volume',$param) && $param['sale_volume'] != 'undefined'){
            $data['sale_volume'] = $param['sale_volume'];
        }else{
            $data['sale_volume'] = 0;
        }
        return $data;
    }

    public function getUser()
    {
        $arr = Session::get('date');
        if($arr){
            $arr['mobile'] = substr($arr['mobile'], 0, 3).'****'.substr($arr['mobile'], 7);
        }
        return $arr;
    }

    public function goodsCates($where = '1 = 1')
    {
        $goodsCateModel = new GoodsCate;
        return $goodsCateModel::where($where)->order('sort asc,id desc')->select();
    }

    public function allGoods($param)
    {
        // dump($param);die;
        $str = 'status = 2';
        if(array_key_exists('keywords',$param)){
            if($param['keywords']){
                $str .= ' AND (title like "%'.$param["keywords"].'%" OR web_address = "'.$param["keywords"].'" OR sp_id = "'.$param["keywords"].'")';
            }
        }
        if(array_key_exists('sale_type',$param)){
            if($param['sale_type'] == 1){
                $str .= ' AND sale_time  < '.time();
            }else{
                $str .= ' AND sale_time  > '.time();
            }
        }else{
            $str .= ' AND sale_time  < '.time();
        }
        if(array_key_exists('cate_id',$param) && $param['cate_id']){
            $str .= ' AND cate_id = '.$param['cate_id'];
        }
        if(array_key_exists('price1',$param) && array_key_exists('price2',$param)){
            $str .= ' AND last_price between '.$param['price1'].' and '.$param['price2'];
        }else if(array_key_exists('price1',$param) && !array_key_exists('price2',$param)){
            $str .= ' AND last_price > '.$param['price1'];
        }else if(!array_key_exists('price1',$param) && array_key_exists('price2',$param)){
            $str .= ' AND last_price < '.$param['price2'];
        }
        if(array_key_exists('coupon_price',$param) && $param['coupon_price']){
            $str .= ' AND coupon_price > '.$param['coupon_price'];
        }
        if(array_key_exists('commision',$param) && $param['commision']){
            $str .= ' AND commision >= '.$param['commision'];
        }
        if(array_key_exists('sale_volume',$param) && $param['sale_volume']){
            $str .= ' AND sale_volume >= '.$param['sale_volume'];
        }
        // dump($str);die;
        $goodsModel = new Goods;
        $count = $goodsModel::where($str)->count();
        $allGoods = $goodsModel::with([
            'seller' => function($query){
                $query->field('id,username');
            }
        ])->where($str)->where('end_time','>',time())->order('add_time desc')->paginate(20,false,[
            'query' => $param,
            'type'      => 'page\Page',
            'var_page'  => 'page',
        ]);
        // print_r($goodsModel->getLastSql());die;
        $page = $allGoods->render();
        return ['allGoods'=>$allGoods,'page'=>$page,'count'=>$count];
    }

    public function getUserCollect()
    {
        $user = Session::get('date');
        if($user){
            $collectModel = new Collect;
            $userCollect = $collectModel::where(['uid'=>$user['id'],'status'=>1])->column('goods_id');
            return $userCollect;
        }else{
            return [];
        }
    }

    public function collecting($id)
    {
        $user = Session::get('date');
        if(!$user){
            return ['code'=>'0','msg'=>'请先登录'];
        }
        $collectModel = new Collect;
        $myCollect = $collectModel::where(['uid'=>$user['id'],'goods_id'=>$id])->find();
        // dump($myCollect);die;
        $msg = '收藏成功';
        $status = 2;
        if(!$myCollect){
            $info = $collectModel::insert(['uid'=>$user['id'],'goods_id'=>$id,'add_time'=>time()]);
        }else{
            if($myCollect->status == 1){
                // echo $myCollect->id;die;
                $info = $collectModel::where('id',$myCollect->id)->update(['status'=>2]);
                $msg = '取消收藏成功';
                $status = 1;
            }else{
                $info = $collectModel::where('id',$myCollect->id)->update(['status'=>1,'add_time'=>time()]);
            }
        }
        if(!$info){
            return ['code'=>-1,'msg'=>'系统繁忙'];
        }
        return ['code'=>1,'status'=>$status,'msg'=>$msg];
    }

    public function collectParam($param)
    {
        $map = [];
        if(array_key_exists('keywords',$param) && $param['keywords'] != ''){
            $map['keywords'] = $param['keywords'];
        }else{
            $map['keywords'] = 0;
        }
        if(array_key_exists('type',$param) && $param['type'] != 'undefined'){
            $map['type'] = $param['type'];
        }else{
            $map['type'] = 1;
        }
        if(array_key_exists('cate_id',$param) && $param['cate_id'] != 'undefined'){
            $map['cate_id'] = $param['cate_id'];
        }else{
            $map['cate_id'] = 0;
        }
        return $map;
    }

    public function collect($param)
    {
        // dump($param);die;
        $user = Session::get('date');
        if(!$user){
            return ['code'=>-1,'msg'=>'请先登录'];
        }
        $str = 'uid = '.$user['id'].' AND status = 1';

        if(array_key_exists('type',$param)){
            if($param['type'] == 2){
                $today = strtotime(date("Y-m-d"),time());
                $str .= ' AND add_time between '.$today.' and '.time();
            }
        }

        $str_goods = '1 = 1';
        if(array_key_exists('keywords',$param) && $param['keywords'] != ''){
            $str_goods .= ' AND (title like "%'.$param["keywords"].'%" OR web_address = "'.$param["keywords"].'" OR sp_id = "'.$param["keywords"].'")';
        }

        if(array_key_exists('cate_id',$param)){
            if($param['cate_id']){
                // $where['cate_id'] = $param['cate_id'];
                $str_goods .= ' AND cate_id = '.$param['cate_id'];
            }
        }
        $collectModel = new Collect;
        $collects = $collectModel::with([
            'goods' => function($query) use($str_goods){
                $query->with('seller')->where($str_goods);
            }
        ])->where($str)->select();
        // dump($collects);die;
        foreach($collects as $k=>$v){
            if(empty($v->goods)){
                unset($collects[$k]);
            }
            if(array_key_exists('type',$param) && $param['type'] == 3){
                // echo 444;die;
                if(!empty($v->goods) && $v->goods->end_time > time()){
                    unset($collects[$k]);
                }
            }
        }
        return $collects;
    }

    public function getUserOrder()
    {
        $userModel = new User;
        $users = $userModel::where('session_key','neq','')->column('id,session_key');
        $tiem = date('Y-m-d H:i:s',time()-1200);//获取当前时间20分钟之前的时间
        // $tiem = '2018-12-25 14:50:17';
        $daytime= date("Y-m-d H:i:s", strtotime("-20 day")-1200);//获取20天之前当前时间的20分钟之前的时间
        $orderModel = new Order;
        $goodsModel = new Goods;
        foreach($users as $k=>$v){
            // sleep(1);
            $this->getOrder($k,$v,$tiem,1,$orderModel,$goodsModel);//获取20分钟之内的订单
            $this->getOrder($k,$v,$daytime,2,$orderModel,$goodsModel);//获取20天之前的订单
        }
    }

    public function getOrder($uid,$session,$tiem,$type,$orderModel,$goodsModel)
    {
        $str = urlencode($tiem);
        $url = 'http://api.tkurl.top/tbk_order?appkey=VYnPTEkn&start_time='.$str.'&span=1200&session='.$session;
        $ch = curl_init();
        curl_setopt ($ch, CURLOPT_URL, $url);
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT,10);
        $dxycontent = curl_exec($ch);
        curl_close($ch);
        $data = json_decode ($dxycontent,true,512,JSON_BIGINT_AS_STRING);
        // dump($data);
        // Cache::set($uid,$data,3600);
        // $data = Cache::get($uid);
        if(!empty($data['tbk_sc_order_get_response']['results'])){
            $this->keepOrder($uid,$data['tbk_sc_order_get_response']['results']['n_tbk_order'],$type,$orderModel,$goodsModel);
        }
        return true;
    }

    public function keepOrder($uid,$data,$type,$orderModel,$goodsModel)
    {
        // Log::write(3);
        $arr = [];
        $times = time();
        foreach($data as $k=>$v){
            $order = $orderModel::where('trade_id',$v['trade_id'])->find();
            $goods = $goodsModel::where('sp_id',$v['num_iid'])->find();
            if($type == 1){//保存当前20分钟之内的订单
                if(empty($order) && !empty($goods) && $goods->end_time < time()){
                    $v['uid'] = $uid;
                    $v['create_time'] = strtotime($v['create_time']);
                    $v['add_time'] = $times;
                    $arr[] = $v;
                }
            }else{//更新20天之前当前时间20分钟之内的订单
                if(!empty($order)){
                    $arr1 = [
                        'id'          => $order->id,
                        'tk_status'   => $v['tk_status'],
                        'update_time' => $times,
                    ];
                    $arr[] = $arr1;
                }
            }
        }
        // dump($arr);die;
        if(!empty($arr)){
            $orderModel->saveAll($arr);
        }
        return true;
    }
}
